package easymall.controller.admin;

import easymall.clients.CategoryService;
import easymall.po.Category;
import easymall.pojo.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class CategoryControllerAdmin {
    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/admin/prodclass")
    public String prodClass(Integer page, Model model) {
        int totalPage = categoryService.getTotalPage(); // 获取总页数
        if (page == null || page < 1)
            page = 1;
        if (page > totalPage)
            page = totalPage;

        List<Category> categorys = categoryService.getCategorysByPage(page);
        model.addAttribute("categorys", categorys);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("page", page);

        return "admin/prod_class";
    }

    @RequestMapping("/admin/prodclassadd")
    public String addProdClass(Integer id, String name, Model model) {
        if (name != null)
            model.addAttribute("name", name);
        if (id != null)
            model.addAttribute("id", id);
        return "admin/prod_class_add";
    }

    @RequestMapping("/admin/saveprodclass")
    @ResponseBody
    public ResponseMessage saveProdClass(Category category) {

        ResponseMessage res = new ResponseMessage();

        if (category.getId() != null) { // 修改
//			int ans = productsService.updateCategory(new Category(id,name));
            res.setCode(categoryService.updateCategory(category));
        } else { // 新增
            res.setCode(categoryService.saveCategory(category.getName()));
        }

        return res;
    }

    // 删除商品类别
    @RequestMapping("/admin/delprodclass")
    @ResponseBody
    public ResponseMessage delProClass(Integer id) {
        ResponseMessage res = new ResponseMessage();
        res.setCode(categoryService.delCategory(id));
        return res;
    }
}
